package com.example.rbac.controller.restful;

import com.example.rbac.entity.*;
import com.example.rbac.entity.defefult.Result;
import com.example.rbac.mapper.cache.RedisDao;
import com.example.rbac.service.MenuService;
import com.example.rbac.service.RoleService;
import com.example.rbac.uitls.ResultUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2017/10/16.
 */
@RestController
@RequestMapping("/api/Role")
public class RoleRestController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    @GetMapping("getList")
    public Result<Role> findList(){
        return ResultUtil.success(roleService.findList());
    }

    @GetMapping("getMenuList")
    public List<Map<String, Object>>  findMenuList(String id){
        List<Menu> menuList = menuService.findMenuListByRoleId(id);
        List<Map<String, Object>> mapList = Lists.newLinkedList();
        for (Menu menu : menuList){
            Map<String, Object> map = Maps.newLinkedHashMap();
            map.put("id", menu.getId());
            map.put("pId", menu.getPid());
            map.put("name", menu.getName());
            map.put("rootPId", menu.getPid()=="0"?menu.getPid():"");
            map.put("checked", menu.getState().equals("1")?"true":"false");
            mapList.add(map);
        }
        return  mapList;
    }

    @PostMapping(value = "/updatePermission", produces = "application/json")
    public Result updatePermission( String id, String[] menuId, String[] state){
        List<RoleMenu> roleMenus = Lists.newLinkedList();
        for (int i = 0; i<menuId.length; i++){
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuId[i]);
            roleMenu.setState(state[i]);
            roleMenus.add(roleMenu);
        }
       return ResultUtil.success(menuService.updateByPermission(id,roleMenus));
    }

    @PostMapping("addRole")
    public Result addRole(Role role){
        return ResultUtil.success(roleService.insertRole(role));
    }


    @GetMapping("/page")
    public Page getPager(Integer pageNum, Integer pageSize){
        Page<Role> roleList;
        if(pageNum == null || pageSize == null){
            pageNum = 1;
            pageSize = 2;
        }
        roleList = roleService.getPager(pageNum, pageSize);
        return roleList;
    }
}
